<?php

namespace App\Plugins\Shh;

use App\Models\Company;
use App\Models\Customer;
use App\Models\Group;
use App\Models\HouseInfo;
use App\Models\Project;
use App\Plugins\Shh\Customer as ShhCustomer;
use App\Plugins\Shh\DB;
use App\Services\AdminService;
use App\Services\HelpService;
use Illuminate\Http\Request;
use \App\Http\Requests\Plugin\ShhRequest;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use MongoDB\BSON\ObjectID;

class ShhController extends Controller
{
    protected $_db;
    protected $_needCheckList;

    public function __construct()
    {
        $this->_db = DB::createDb('plugin_shh', 'customers');
        $this->_needCheckList = config('plugin.SHH.need_checks', null);
    }

    public function index($ssh_key) {
        if (!is_null($this->_needCheckList) && !in_array($ssh_key, $this->_needCheckList)) {
            return [
                'total' => 0,
                'per_page' => 20,
                'current_page' => 1,
                'data' => []
            ];
        }
        $page = request()->input('page', 1);
        $per_page = 20;
        //查询条件
        $filter = [
            'shhKey' => $ssh_key,
            '_v' => 0
        ];
        $data = HelpService::get_filter();
        if(isset($data['query'])) {
            if (is_numeric($data['query'])) {
                $filter['$or'] = [
                    ['mobile' => ['$elemMatch' => ['$regex' => (string) $data['query']]]],
                    ['cid' => (int) $data['query']],
                ];
            } else {
                $filter['name'] = [
                    '$elemMatch' => ['$regex' => $data['query']]
                ];
            }
        }
        //分页
        $limit = [
            'limit' => $per_page,
            'skip' => ($page - 1) * $per_page,
            'sort' => ['cid' => 1],
        ];
        $cursor = $this->_db->find($filter, $limit);
        $data = [];
        foreach ($cursor as $customer) {
            $customer_obj = new ShhCustomer($customer);
            array_push($data, $customer_obj->getInfo());
        }
        $total = $this->_db->count($filter);
        $res_data = [
            'total' => $total,
            'per_page' => 20,
            'current_page' => $page,
            'data' => $data,
        ];
        return $res_data;
    }

    public function show($cid) {
        $customer = $this->_db->findOne(['cid' => (int) $cid]);
        if (!$customer) {
            return $this->_error('该客户不存在');
        }
        $customer_obj = new ShhCustomer($customer);
        return $customer_obj->getInfo();
    }

    public function update(Request $request, $cid) {
        $data = $request->all();
        //$data = HelpService::getRequest($data);
        $user = Auth::User();
        $customer = Customer::where([
            'baseInfo.mobile' => $data['mobile'],
        ])->first();
        $info = [];
        $info['shhKey'] = $data['shhKey'];
        $info['authType'] = '';
        $info['address'] = $data['address'];
        $project_id = $data['projects'][0];
            $project = Project::where('id', $project_id)
                ->get();
            if (!$project) {
                return $this->_error('该项目不存在。');
            }
            $users = $project->pluck('users')->flatten()->all();
            if (!in_array($user->id, $users)) {
                $this->_error('权限不足，不可操作此项目。');
            }

        if ($customer) {
            if ($customer->baseInfo['name'] === $data['name']) {
                $house_info_list = $customer['houseInfo'] ?? [];
                // 房屋地址去重
                $house_adds = [];
                // 提交过来的房屋地址
                $addInfo = implode('', $info['address']);
                if (!empty($house_info_list)) {
                    foreach ($house_info_list as $v) {
                        array_push($house_adds, implode('', $v['address']));
                    }
                }
                // 提交过来的地址不存在此客户的房屋信息中  则新建房屋信息
                if (!in_array($addInfo, $house_adds)) {
                    $house_info = new HouseInfo();
                    $house_info = $house_info->create($info);
                    array_push($house_info_list, $house_info);
                }
                $customer->houseInfo = $house_info_list;
                $projects = $customer->projects ?? [];
                if (in_array($project_id, $projects)) {
                    $data['projects'] = [];
                }
                $projects = array_merge($projects, $data['projects']);
                $customer->projects = $projects;
                // 把cid保存到socialInfo中的shihui中的id中
                $socialInfo = [];
                $socialInfo['shihui']['id'] = $cid;
                $customer->socialInfo = $socialInfo;

            } else {
                return $this->_error('该手机号已存在。');
            }
        } else {
            $customer = new Customer();
            $baseInfo = $customer->baseInfo;
            $baseInfo["name"] = $data['name'];
            $baseInfo["mobile"] = $data['mobile'];
            $customer->baseInfo = $baseInfo;
            $house_info = new HouseInfo();
            $house_info = $house_info->create($info);
            $customer->houseInfo = [$house_info];
            $customer->projects = $data['projects'];
            // 把cid保存到socialInfo中的shihui中的id中
            $socialInfo = [];
            $socialInfo['shihui']['id'] = $cid;
            $customer->socialInfo = $socialInfo;
        }
        $isSave = $customer->save();
        if ($isSave) {
            $this->_db->updateMany([
                'cid' => (int) $cid,
            ], ['$set' => ['_v' => time()]]);
            //操作员自动认领 todo: 第二版要根据判断当前登录的人的账号是否是最底层账号  这一版不考虑  直接认领
            $filter['company_id'] = $user->company_id;
            $filter['project_id'] = $project_id;
            $filter['customer_id'] = $customer->id;
            $filter['user_id'] = $user->id;
            //调用更新认领表逻辑
            $admin_service = new AdminService();
            $admin_service->updateAcceptRecord($filter);
            $customer->houseInfo = array_map(function ($house_info) {
                $house_info['_id'] = (string) $house_info['_id'];
                return $house_info;
            }, $customer->houseInfo);
            return $customer;
        } else {
            return $this->_error('保存失败');
        }
    }

    /**
     * 实惠服务社列表
     * @return array|mixed
     */
    function community()
    {
        $data = HelpService::getFileContent('community_list', 'community/');
        return [
            'total' => count($data),
            'data' => $data,
        ];
    }

    /**
     * 客户所属服务社列表
     * @param $project_ids
     * @return array
     */
    function customerCommunity($project_ids)
    {
        $user = Auth::User();
        $items = [];
        $project_ids = explode('|', $project_ids);
        $projects = [];
        //取出客户参与的实惠相关项目
        foreach ($project_ids as $project_id) {
            $project = Project::find($project_id);
            if (!is_null($project) && $plugins = $project->plugins) {
                if (array_key_exists('shihui', $plugins)) {
                    array_push($projects, $project);
                }
            }
        }
        if (count($projects)) {
            $user_group = Group::find($user->group_id);
            $groups = $user_group->getLeafBy();
            $group_id = [];
            if (is_array($groups)) {
                foreach ($groups as $group) {
                    array_push($group_id, $group->id);
                }
            } else {
                array_push($group_id, $groups->_id);
            }

            foreach ($projects as $project) {
                if (in_array($project->group_id, $group_id)) {
                    array_push($items, $project->plugins['shihui']['key']);
                }
            }
            //获取对应服务社信息
            if (count($items)) {
                $items = array_unique($items);
                $result = HelpService::getFileContent($items, 'community/json/');
                return [
                    'total' => count($result),
                    'data' => array_values($result),
                ];
            } else {
                return HelpService::emptyListReturn();
            }
        } else {
            return HelpService::emptyListReturn();
        }
    }
}
